package io.github.igordonxiao.gateguard.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.igordonxiao.gateguard.domain.User;
import io.github.igordonxiao.gateguard.exception.UserExceptions;
import io.github.igordonxiao.gateguard.service.UserService;
import io.github.igordonxiao.gateguard.util.ObjectUtil;
import io.github.igordonxiao.gateguard.util.SecurityUtils;
import io.github.igordonxiao.gateguard.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

import static io.github.igordonxiao.gateguard.config.Const.DEFAULT_PAGE_NO;
import static io.github.igordonxiao.gateguard.config.Const.DEFAULT_PAGE_SIZE;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    PasswordEncoder passwordEncoder;

    @GetMapping
    ResponseEntity<IPage<User>> list(@RequestParam(required = false) Integer pageNo,
                                     @RequestParam(required = false) Integer pageSize) {
        if (pageNo == null) {
            pageNo = DEFAULT_PAGE_NO;
        }
        if (pageSize == null) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        return ResponseEntity.ok(userService.lambdaQuery().orderByDesc(User::getCreatedTime).page(new Page<>(pageNo, pageSize)));
    }


    @PostMapping
    ResponseEntity<UserVo> saveUser(@RequestBody User user) {
        if (userService.findUserByCode(user.getCode()) != null) {
            throw UserExceptions.DUPLICATE_USER_CODE;
        }
        if (userService.findUserByName(user.getName()) != null) {
            throw UserExceptions.DUPLICATE_USER_NAME;
        }
        String id = user.getId();
        if (StringUtils.isEmpty(id)) {
            user.setId(UUID.randomUUID().toString());
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            userService.save(user);
            return ResponseEntity.ok(ObjectUtil.domainToVo(user, UserVo.class));
        } else {
            User dbUser = userService.getById(id);
            dbUser.setCode(user.getCode());
            dbUser.setName(user.getName());
            userService.updateById(dbUser);
            return ResponseEntity.ok(ObjectUtil.domainToVo(dbUser, UserVo.class));
        }
    }


    @GetMapping("info")
    ResponseEntity<UserVo> userInfo() {
        return ResponseEntity.ok(ObjectUtil.domainToVo(userService.getById(SecurityUtils.getLoginUserId()), UserVo.class));
    }

    @DeleteMapping("/{id}")
    ResponseEntity<Boolean> deleteResidentById(@PathVariable String id) {
        if (SecurityUtils.getLoginUserId().equalsIgnoreCase(id)) {
            throw UserExceptions.CAN_NOT_DELETE_SELF;
        }
        return ResponseEntity.ok(userService.removeById(id));
    }

}
